<template>
  <div class="paly-audio">
    <div class="page-audio-dom">
      <div :class="disabled ? 'not-click' : 'click'" @click="handleClickPlayAudio" v-if="type == 0"
        class="img-box img-box-1">
        <img v-if="!isPlaying" style="width: 24px; height: 21px;" src="../assets/img/card-play.png" alt="" />
        <img v-if="isPlaying" style="width: 24px; height: 21px;" src="../assets/img/audio-paly-green-0.gif" alt="" />
      </div>
      <div :class="disabled ? 'not-click' : 'click'" @click="handleClickPlayAudio" v-if="type == 1"
        class="img-box img-box-1">
        <img v-if="!isPlaying" :style="{width: size[0], height: size[1]}" src="../assets/img/icon-audio.png" alt="" />
        <img v-if="isPlaying" :style="{width: size[0], height: size[1]}" src="../assets/img/audio-paly-green.gif" alt="" />
      </div>

      <div :class="disabled ? 'not-click' : 'click'" @click="handleClickPlayAudio" v-if="type == 2"
        class="img-box img-box-2">
        <img v-if="isPlaying" src="../assets/img/audio=play-or.gif" alt="" />
        <img v-if="!isPlaying" src="../assets/img/icon-audio-or.png" alt="" />
      </div>
      <div :class="disabled ? 'not-click' : 'click'" @click="handleClickPlayAudio" v-if="type == 6"
        class="img-box img-box-1">
        <img v-if="isPlaying" :style="{width: size[0], height: size[1]}" src="../assets/img/naturalSpell/audio-paly-green-6.gif" alt="" />
        <img v-if="!isPlaying" :style="{width: size[0], height: size[1]}" src="../assets/img/naturalSpell/audio-paly-green-6.png" alt="" />
      </div>
      <div v-if="type == 3">
        <div :class="disabled ? 'not-click' : 'click'" @click="handleClickPlayAudio" v-show="isPlaying">
          <slot name="pause"></slot>
        </div>
        <div :class="disabled ? 'not-click' : 'click'" @click="handleClickPlayAudio" v-show="!isPlaying">
          <slot name="play"></slot>
        </div>
      </div>
      <div :class="disabled ? 'not-click' : 'click'" @click="handleClickPlayAudio" v-if="type == 4"
        class="img-box img-box-4">
        <img v-if="!isPlaying" src="../assets/img/icon-audio-s.png" alt="" />
        <img v-show="isPlaying" src="../assets/img/audio-paly-green-s.gif" alt="" />
      </div>
      <div v-if="type == 5" class="audio-controls record">
        <slot name="controls-custom">
          <span class="right-audio click" @click="
            isPlaying ? handleClickPauseAudio() : handleClickPlayAudio()
            ">
            <i v-if="isPlaying" class="font_family icon-zanting"></i>
            <i v-if="!isPlaying" class="font_family icon-bofang"></i>
          </span>
          <div class="audio-progress">
            <div class="progress-bg">
              <div :style="`width: ${(bufferedTime / totalTime) * 100}%`" class="progress-buffer"></div>
              <div :style="`width: ${(currentTime / totalTime) * 100}%`" class="progress-play"></div>
            </div>
          </div>
          <span class="audio-time">{{ currentAudioTime | filterTime(2, "m") }} /{{
            totalAudioTime | filterTime(2, "m")
          }}
          </span>
        </slot>
      </div>
    </div>
    <!--  @progress="audioProgress" -->
    <audio ref="audioDom" @play="handleAudioPlay" @pause="handleAudioPause" @ended="handleAudioEnded"
      @timeupdate="timeupdate" @canplay="canplay" :src="audioSrc"></audio>
  </div>
</template>
<script>
// import { throttle1 } from "../utils/utils";
export default {
  data() {
    return {
      speed:1,
      isPlaying: false,
      totalTime: 0,
      currentTime: 0,
      bufferedTime: 0,
      endTime: null,
    };
  },
  computed: {
    currentAudioTime() {
      return this.currentTime;
    },
    totalAudioTime() {
      return this.totalTime;
    },
  },
  methods: {
    async handleAudioPlay() {
      console.log(11111);
      // 播放音频开始
      // if ((this.$route.path.indexOf("/sentence/") != -1 || this.$route.path.indexOf("/text/") != -1)&&localStorage.getItem("SPEED")) {
      //     this.$refs.audioDom.playbackRate = localStorage.getItem("SPEED")
      // }
      // await this.$nextTick()
      this.isPlaying = true;
      console.log(
        "startTime:",
        this.$refs.audioDom && this.$refs.audioDom.currentTime
      );
      this.$emit("audioStart");
    },
    handleAudioEnded() {
      // 播放音频结束
      // console.log("handleAudioPlayEnded");
      this.isPlaying = false;
      console.log(
        "endTime:",
        this.$refs.audioDom && this.$refs.audioDom.currentTime
      );
      this.$emit("audioEnded");
    },
    handleAudioPause() {
      // 播放音频暂停
      // console.log("handleAudioPause");
      this.isPlaying = false;
      console.log(
        "pauseTime:",
        this.$refs.audioDom && this.$refs.audioDom.currentTime
      );
      this.$emit("audioPause");
    },
    handleClickPlayAudio() {
      if (!this.isClick) {
        return;
      }
      if (this.$refs.audioDom && this.isPlaying) {
        if (this.isAllowPause) {
          this.$refs.audioDom.pause();
        } else {
          this.$refs.audioDom.currentTime = 0;
        }
      } else {
        this.playAudio(this.audioStartTime, this.audioEndTime);
      }
    },
    handleClickPauseAudio() {
      if (!this.isClick) {
        return;
      }
      this.pauseAudio();
    },
    playAudio(currentTime, endTime) {
      if (endTime) {
        this.endTime = endTime;
      } else {
        this.endTime = null;
      }
      if (this.disabled) {
        return;
      }
      if (this.$refs.audioDom) {
        this.$pauseAllAudio();
        this.$pauseAllVideo();
        if (this.$refs.audioDom.readyState === 0) {
          this.$emit("playError", this.$refs.audioDom.readyState);
        }
        let timer = setTimeout(() => {
          // console.log(currentTime, this.bufferedTime);
          if (
            typeof currentTime === "number" &&
            !isNaN(currentTime) &&
            currentTime >= 0 &&
            currentTime <= this.totalTime
          ) {
            this.$refs.audioDom.currentTime = currentTime;
          }
          this.$refs.audioDom.play();
          clearTimeout(timer);
        }, 150);
      }
    },
    pauseAudio() {
      if (this.$refs.audioDom) {
        this.$refs.audioDom.pause();
      }
    },
    initAudioPlay() {
      this.isPlaying = false;
      this.$refs.audioDom.load();
      this.$refs.audioDom.playbackRate = this.speed
    },
    audioProgress() {
      console.log(this.$refs.audioDom.buffered);
      // this.bufferedTime = this.$refs.audioDom.buffered.end(
      //   this.$refs.audioDom.buffered.length - 1
      // );
    },
    // timeupdate: throttle1(function () {
    //   this.currentTime = this.$refs.audioDom && this.$refs.audioDom.currentTime;
    //   if (this.endTime && this.currentTime > this.endTime) {
    //     console.log(this.endTime, this.currentTime);
    //     this.pauseAudio();
    //   }
    //   this.$emit("timeupdate", this.currentTime);
    // }, 0),
    timeupdate: function () {
      this.currentTime = this.$refs.audioDom && this.$refs.audioDom.currentTime;
      if (this.endTime && this.currentTime > this.endTime) {
        this.pauseAudio();
      }
      this.$emit("timeupdate", this.currentTime);
    },
    canplay() {
      this.totalTime = this.$refs.audioDom && this.$refs.audioDom.duration;
    },
  },
  async mounted() { 
    if(this.$route.path.indexOf("sentence") != -1 || this.$route.path.indexOf("/text/") != -1){
      this.speed=Number(localStorage.getItem("SPEED"))||1
    }
    this.initAudioPlay();
  },
  beforeDestroy() { },
  props: {
    // 页面展示图标
    type: {
      type: Number,
      default: 2,
    },
    // 是否允许暂停
    isAllowPause: {
      type: Boolean,
      default: false,
    },
    // 是否禁止点击
    disabled: {
      type: Boolean,
      default: false,
    },
    isClick: {
      type: Boolean,
      default: true,
    },
    // 音频属性
    // 地址
    audioSrc: {
      type: String,
      default: "",
      // "http://tts.baidu.com/text2audio?lan=en&ie=UTF-8&spd=2&text='My name is Ben. This is my family photo. This boy is me. My father is a doctor. He likes reading newspapers very much. My mother is an engineer. She likes reading books. This is my little sister. She is five years old. She likes collecting toys. She has two teddy bears and three toy cats. I like playing football. I often play it with my friends on Saturdays and Sundays.'",
    },
    audioStartTime: {
      default: null,
    },
    audioEndTime: {
      default: null,
    },
    size:{
      type:Array,
      default: () =>["auto","auto"]
    }
    // 是否静音 muted

    // 音量 volume  规定音频/视频的当前音量。必须是介于 0.0 与 1.0 之间的数字。
    // 播放速度 playbackRate
    /**
     *  1.0 正常速度
        0.5 半速（更慢）
        2.0 倍速（更快）
        -1.0 向后，正常速度
        -0.5 向后，半速
     */
  },
  watch: {
    audioSrc() {
      this.initAudioPlay();
    },
    isPlaying() {
      this.$emit("onIsPlay", this.isPlaying);
    },
  },
};
</script>
